package com.atguigu.chapter07.D03_Timer;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/8/7
 * Desc:
 */
public class Flink01_Timer_ProcessTime {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        // 测试取消的时候，为了让他们互相不影响，将并行度设置为2
        env.setParallelism(1);

        // 当水位超过10 ，5s后发出预警
        // 注意：定时器是和key绑定在一起的，必须先keyBy   而且不同key的定时器，只能取消自己的取消不了别人的
        env
                .socketTextStream("hadoop101", 9999) // socket只能是1
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {

                    private long ts;

                    @Override
                    public void processElement(WaterSensor value,
                                               Context ctx,
                                               Collector<String> out) throws Exception {
                        if (value.getVc() > 10) {
                            // 注册定时器，基于处理时间的定时器
                            ts = System.currentTimeMillis() + 5000;
                            System.out.println("注册定时器：" + ts);
                            ctx.timerService().registerProcessingTimeTimer(ts);
                        } else if (value.getVc() < 10) {
                            System.out.println("取消定时器：" +ts);
                            ctx.timerService().deleteProcessingTimeTimer(ts);
                        }
                    }

                    // 触发定时器后执行的方法
                    // 参数1：定时器触发的时间
                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<String> out) throws Exception {
                        out.collect(ctx.getCurrentKey() + "的水位超过10，发出警告...");
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
